package com.slwish.xty.ui.activity;

import android.Manifest;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.provider.MediaStore;
import android.view.View;

import com.allen.library.SuperTextView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.google.gson.Gson;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.compress.Luban;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.tools.PictureFileUtils;
import com.othershe.nicedialog.BaseNiceDialog;
import com.othershe.nicedialog.SelectionDialog;
import com.othershe.nicedialog.interf.DialogInterface;
import com.slwish.common.base.PresenterToolbarActivity;
import com.slwish.common.config.Contants;
import com.slwish.common.interf.PerfectClickListener;
import com.slwish.common.utils.FileUtils;
import com.slwish.common.utils.IntentUtils;
import com.slwish.common.utils.SpUtils;
import com.slwish.common.utils.TimeUtils;
import com.slwish.xty.R;
import com.slwish.xty.db.UserDb;
import com.slwish.xty.entity.CityModel;
import com.slwish.xty.entity.UserModel;
import com.slwish.xty.mvp.contract.UserInfoContract;
import com.slwish.xty.mvp.presenter.UserInfoPresenter;
import com.slwish.xty.utils.DialogUtils;
import com.slwish.xty.utils.GetJsonDataUtil;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionNo;
import com.yanzhenjie.permission.PermissionYes;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class UserInfoActivity extends PresenterToolbarActivity<UserInfoContract.Presenter> implements UserInfoContract.View {
    @BindView(R.id.tv_head)
    SuperTextView tvhead;
    @BindView(R.id.tv_name)
    SuperTextView tvName;
    @BindView(R.id.tv_birthday)
    SuperTextView tvBirthday;
    @BindView(R.id.tv_sex)
    SuperTextView tvSex;
    @BindView(R.id.tv_city)
    SuperTextView tvCity;
    @BindView(R.id.tv_smrz)
    SuperTextView tvSmrz;
    @BindView(R.id.tv_phone)
    SuperTextView tvPhone;
    private int choose;//选择相机还是相册
    private String cameraPath;//拍照的照片路径
    private List<LocalMedia> selectImageList;
    private List<CityModel> options1Items = new ArrayList<>();
    private List<ArrayList<String>> options2Items = new ArrayList<>();
    private List<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();
    private UserModel userModel;
    private Thread thread;

    @Override
    protected int getLayoutId() {
        return R.layout.act_user_info;
    }

    @Override
    protected void initWidget() {
        super.initWidget();
        setTitle(R.string.user_info_title);
        setRightIcon(R.mipmap.set);
        long userId = SpUtils.getLong(mContext, Contants.UserCode, 0);
        userModel = UserDb.query(userId + "");
        if (userModel != null) {
            tvBirthday.setRightString(userModel.getBirthday().equals("")?"未设置":userModel.getBirthday());
            tvName.setRightString(userModel.getNickname().equals("")?"未设置":userModel.getNickname());
            tvPhone.setRightString(userModel.getMobile().equals("")?"未设置":userModel.getMobile());
            tvSex.setRightString(userModel.getSex().equals("")?"未设置":userModel.getSex());
//            tvSmrz.setRightString(userModel.g)
            tvCity.setRightString(userModel.getCity().equals("")?"未设置":userModel.getCity());
            RequestOptions options = RequestOptions.circleCropTransform()
                    .placeholder(R.mipmap.touxiang88)
                    .error(R.mipmap.touxiang88);
            if (userModel.getPhoto() == null || userModel.getPhoto().equals("")) {
                tvhead.setRightTvDrawableRight(getResources().getDrawable(R.mipmap.touxiang88));
            } else {
                Glide.with(mContext)
                        .load(userModel.getPhoto())
                        .apply(options)
                        .into(new SimpleTarget<Drawable>() {
                            @Override
                            public void onResourceReady(Drawable resource, Transition<? super Drawable> transition) {
                                tvhead.setRightTvDrawableRight(resource);
                            }
                        });
            }

        }

        if (thread == null) {//如果已创建就不再重新创建子线程了
//            Toast.makeText(JsonDataActivity.this,"Begin Parse Data",Toast.LENGTH_SHORT).show();
            thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    // 写子线程中的操作,解析省市区数据
                    initJsonData();
                }
            });
            thread.start();
        }
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        EventBus.getDefault().post("closeDrawer");
        setRightOnClickListener(new PerfectClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                IntentUtils.startActivity(mContext, SettingActivity.class);
            }
        });
    }

    @Override
    protected UserInfoContract.Presenter initPresenter() {
        return new UserInfoPresenter(this);
    }

    @OnClick({R.id.btn_login_out, R.id.tv_name, R.id.tv_head, R.id.tv_birthday, R.id.tv_sex, R.id.tv_city, R.id.tv_smrz, R.id.tv_phone})
    public void setOnClick(View view) {
        switch (view.getId()) {
            case R.id.btn_login_out:
                SpUtils.clear(mContext);//清空保存的所有数据
                //本地数据库数据删除
                UserDb.delete(userModel.getUserId());
                SpUtils.put(mContext, Contants.FIRST_OPEN, false);
                userModel = new UserModel();
                EventBus.getDefault().post(userModel);
                finish();
                break;
            case R.id.tv_head://修改头像
                showChooseFileDialog();
                break;
            case R.id.tv_sex://修改性别
                showSexDialog();
                break;
            case R.id.tv_birthday://修改生日
//                showChooseFileDialog();
                DialogUtils.showTimePickerDialog(mContext, new DialogUtils.OnItemSelectListener() {
                    @Override
                    public void OnItemSelect(Date time, View v) {
                        String date2String = TimeUtils.date2String(time, TimeUtils.NO_HOUR_SDF);
                        tvBirthday.setRightString(date2String);
                    }
                });
                break;
            case R.id.tv_city://修改城市
//                showChooseFileDialog();
                DialogUtils.showCityPickerView(mContext, options1Items, options2Items, options3Items,
                        new DialogUtils.OnOptionSelectListener() {
                            @Override
                            public void onOptionsSelect(int position1, int position2, int position3, View v) {
                                String city = options1Items.get(position1).getPickerViewText() +
                                        options2Items.get(position1).get(position2) +
                                        options3Items.get(position1).get(position2).get(position3);
                                tvCity.setRightString(city);
                            }
                        });
                break;
            case R.id.tv_name:
                IntentUtils.startActivityForResult(mContext, ModifyNameActivity.class, Contants.MULTIPLE_ACCESS_APPLICATION);
                break;
            case R.id.tv_smrz:
                IntentUtils.startActivityForResult(mContext, RealNameAuthentActivity.class, Contants.REQUESTCODE_REAL_NAME_AUTH);
                break;
            case R.id.tv_phone:
                IntentUtils.startActivity(mContext, PhoneBindingActivity.class);
                break;
        }
    }

    /**
     * 选择性别
     */
    private void showSexDialog() {
        final String[] chooseArray = getResources().getStringArray(R.array.choose_sex);
        DialogUtils.showBottomDialog(mContext, chooseArray,
                new DialogInterface.OnItemClickListener<SelectionDialog>() {
                    @Override
                    public void onItemClick(BaseNiceDialog dialog, View button, int position) {
                        dialog.dismiss();
                        tvSex.setRightString(chooseArray[position]);
                        mPresenter.newSex(mContext, chooseArray[position], userModel.getToken());
//                        Toast.makeText(mContext, chooseArray[position], Toast.LENGTH_SHORT).show();
                    }
                });
    }

    /**
     * 选择上传头像方式
     */
    private void showChooseFileDialog() {
        final String[] chooseArray = getResources().getStringArray(R.array.choose_head);
        DialogUtils.showBottomDialog(mContext, chooseArray,
                new DialogInterface.OnItemClickListener<SelectionDialog>() {
                    @Override
                    public void onItemClick(BaseNiceDialog dialog, View button, int position) {
                        dialog.dismiss();
                        choose = position;
                        checkMediaPermission();
                    }
                });
    }

    // 成功回调的方法，用注解即可，这里的300就是请求时的requestCode。
    @PermissionYes(Contants.MULTIPLE_ACCESS_APPLICATION)
    private void getPermissionYes(List<String> grantedPermissions) {
        // 权限申请成功回调。
        if (choose == 0)//相册
            chosePic(choose);
        else//选相机
            startOpenCamera();

    }

    @PermissionNo(Contants.MULTIPLE_ACCESS_APPLICATION)
    private void getPermissionNo(List<String> deniedPermissions) {
        // TODO 申请权限失败。
        if (AndPermission.hasAlwaysDeniedPermission(UserInfoActivity.this, deniedPermissions)) {
            //  第一种：用默认的提示语。
            AndPermission.defaultSettingDialog(UserInfoActivity.this, Contants.MULTIPLE_ACCESS_APPLICATION).show();
            // 存在数据则选中记住密码
        }
    }

    /**
     * 打开相机
     */
    public void startOpenCamera() {
        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (cameraIntent.resolveActivity(getPackageManager()) != null) {
            File cameraFile = PictureFileUtils.createCameraFile(this, PictureConfig.TYPE_IMAGE,
                    "");
            cameraPath = cameraFile.getAbsolutePath();
            Uri imageUri = FileUtils.parUri(mContext, cameraFile);
            cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
            startActivityForResult(cameraIntent, PictureConfig.REQUEST_CAMERA);
        }
    }

    /**
     * 检查权限
     */
    private void checkMediaPermission() {
        AndPermission.with(UserInfoActivity.this)
                .requestCode(Contants.MULTIPLE_ACCESS_APPLICATION)
                .permission(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .callback(UserInfoActivity.this)
                .start();
    }

    /**
     * 选择相册中照片
     */
    private void chosePic(int chosse) {
        // 进入相册 以下是例子：不需要的api可以不写
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                .theme(R.style.picture_style)// 主题样式设置 具体参考 values/styles   用法：R.style.picture.white.style
//                .maxSelectNum(chosse == 1 ? maxSelectNum : 1)// 最大图片选择数量
                .maxAudioSelectNum(1)// 最大语音选择数量
                .maxVideoSelectNum(1)// 最大视频选择数量
                .minSelectNum(1)// 最小选择数量
                .imageSpanCount(4)// 每行显示个数
                .selectionMode(PictureConfig.SINGLE)// 多选 or 单选
                .compressGrade(Luban.THIRD_GEAR)// luban压缩档次，默认3档 Luban.FIRST_GEAR、Luban.CUSTOM_GEAR
                .isCamera(false)// 是否显示拍照按钮
                .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                .compress(true)// 是否压缩
                .glideOverride(100, 100)// glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
                .showCropFrame(true)// 是否显示裁剪矩形边框 圆形裁剪时建议设为false
                .showCropGrid(false)// 是否显示裁剪矩形网格 圆形裁剪时建议设为false
                .enableCrop(true)
                .cropWH(200, 200)
                .withAspectRatio(1, 1)
//                .minimumCompressSize(100)// 小于100kb的图片不压缩
//                .selectionMedia(chosse == 1 ? selectImageList : selectAudioList)// 是否传入已选图片
                .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
    }

    /**
     * 回调
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        File file = null;
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调
                    selectImageList = PictureSelector.obtainMultipleResult(data);
                    if (selectImageList != null && selectImageList.size() > 0) {
                        cameraPath = selectImageList.get(0).getPath();
                        file = new File(cameraPath);
                    }
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                    // 如果裁剪并压缩了，已取压缩路径为准，因为是先裁剪后压缩的
//                    LogUtils.i("xx", "onActivityResult:" + selectImageList.size());
                    break;
                case PictureConfig.REQUEST_CAMERA:
                    file = new File(cameraPath);
                    sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
                    break;
                default:
                    if (file != null)
                        mPresenter.uploadPhoto(mContext, file);
//                        uploadPhotoSuccess("");
                    else showError(R.string.toast_user_info_upload_photo_null);
                    break;
            }

        } else if (resultCode == Contants.RESULT_CODE) {
//            case Contants.MULTIPLE_ACCESS_APPLICATION://更新昵称
            if (data != null) {
                String nickname = data.getStringExtra("Nickname");
                tvName.setRightString(nickname);
            }
//                break;
        }
    }

    /**
     * 更新头像成功
     *
     * @param URL
     */
    @Override
    public void uploadPhotoSuccess(String URL) {
        RequestOptions options = RequestOptions.circleCropTransform()
                .placeholder(R.mipmap.touxiang88)
                .error(R.mipmap.touxiang88);
        Glide.with(mContext)
                .load(cameraPath)
                .apply(options)
                .into(new SimpleTarget<Drawable>() {
                    @Override
                    public void onResourceReady(Drawable resource, Transition<? super Drawable> transition) {
                        tvhead.setRightTvDrawableRight(resource);
                    }
                });
        userModel.setPhoto(cameraPath);
        userModel.saveOrUpdate("userid = ?", userModel.getUserId() + "");
        EventBus.getDefault().post(userModel);
    }

    private void initJsonData() {//解析数据
        try {
            /**
             * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
             * 关键逻辑在于循环体
             * */
            String JsonData = new GetJsonDataUtil().getJson(this, "province.json");//获取assets目录下的json文件数据
            List<CityModel> jsonBean = parseData(JsonData);//用Gson 转成实体
            /**
             * 添加省份数据
             *
             * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
             * PickerView会通过getPickerViewText方法获取字符串显示出来。
             */
            options1Items = jsonBean;
            for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
                ArrayList<String> CityList = new ArrayList<>();//该省的城市列表（第二级）
                ArrayList<ArrayList<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）
                for (int c = 0; c < jsonBean.get(i).getCityList().size(); c++) {//遍历该省份的所有城市
                    String CityName = jsonBean.get(i).getCityList().get(c).getName();
                    CityList.add(CityName);//添加城市
                    ArrayList<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表
                    //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                    if (jsonBean.get(i).getCityList().get(c).getArea() == null
                            || jsonBean.get(i).getCityList().get(c).getArea().size() == 0) {
                        City_AreaList.add("");
                    } else {
                        for (int d = 0; d < jsonBean.get(i).getCityList().get(c).getArea().size(); d++) {//该城市对应地区所有数据
                            String AreaName = jsonBean.get(i).getCityList().get(c).getArea().get(d);
                            City_AreaList.add(AreaName);//添加该城市所有地区数据
                        }
                    }
                    Province_AreaList.add(City_AreaList);//添加该省所有地区数据
                }
                /**
                 * 添加城市数据
                 */
                options2Items.add(CityList);
                /**
                 * 添加地区数据
                 */
                options3Items.add(Province_AreaList);
            }
        } catch (Exception e) {
        }

    }

    public List<CityModel> parseData(String result) {//Gson 解析
        List<CityModel> detail = new ArrayList<>();
        try {
//            detail = (ArrayList<CityModel>) JSON.parseObject(result, new TypeReference<List<CityModel>>(){});
//            detail =  JSON.parseArray(result, CityModel.class);
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                CityModel entity = gson.fromJson(data.optJSONObject(i).toString(), CityModel.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
//            mHandler.sendEmptyMessage(MSG_LOAD_FAILED);
        }
        return detail;
    }
}
